package org.bminfo.migle.parser;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import org.bminfo.migle.wrapper.MiRandaWrapper;

public class Visualization {
	public String deltaTable(HashMap<String, Double> ranked, String mapPath) throws Exception{
//	    <script type="text/javascript">
//	      google.load("visualization", "1", {packages:["columnchart"]});
//	      google.setOnLoadCallback(drawChart);
//	      function drawChart() {
//	        var data = new google.visualization.DataTable();
//	        data.addColumn('string', 'Year');
//	        data.addColumn('number', 'Sales');
//	        data.addColumn('number', 'Expenses');
//	        data.addRows(4);
//	        data.setValue(0, 0, '2004');
//	        data.setValue(0, 1, 1000);
//	        data.setValue(0, 2, 400);
//	        data.setValue(1, 0, '2005');
//	        data.setValue(1, 1, 1170);
//	        data.setValue(1, 2, 460);
//	        data.setValue(2, 0, '2006');
//	        data.setValue(2, 1, 660);
//	        data.setValue(2, 2, 1120);
//	        data.setValue(3, 0, '2007');
//	        data.setValue(3, 1, 1030);
//	        data.setValue(3, 2, 540);
//
//	        var chart = new google.visualization.ColumnChart(document.getElementById('delta'));
//	        chart.draw(data, {width: 400, height: 240, is3D: true, title: 'Company Performance'});
//	        google.visualization.events.addListener(chart, 'select', function() {
//	        	alert('dd');
//		var hre = "DataServlet?"+ "site=" + clickId +"&type=147&startIndex="+InitIndex+"&folderName="+folder;
//	        	window.open("http://www.google.com",'','');
//	  			});
//	      }
//	    </script>
		

		
		
		HashMap<String,String> acc = new Visualization().miRBaseAcc(mapPath + "hsa-mature-miR.fasta");
		
		StringBuilder function = new StringBuilder();
		
		int[][] range = {{-1000,0},{-500,0},{-200,0},{-100,0},{-50,0},{-20,0},{-10,0},{0,0}
				,{10,0},{20,0},{50,0},{100,0},{200,0},{500,0},{1000,0}};
		
		int range_num = range.length;
		
		for(String miRNA: ranked.keySet()){
			if(ranked.get(miRNA)<=0){
				for(int i=0; i<=7; i++){
					if(ranked.get(miRNA) <= range[i][0]){
						range[i][1]++;
						break;
					}
				}
			}else{
				for(int i=range_num-1; i>7; i--){
					if(ranked.get(miRNA) >= range[i][0]){
						range[i][1]++;
						break;
					}
				}
			}
		}
		
		// draw column chart
		function.append("<script type=\"text/javascript\">" + "\n");
		function.append("var barsVisualization;" + "\n");
		
		function.append("google.load(\"visualization\", \"1\", {packages:[\"columnchart,table\"]});" + "\n");
		function.append("google.setOnLoadCallback(drawColumnChart);" + "\n");
		function.append("function drawColumnChart() {" + "\n");
		function.append("var data = new google.visualization.DataTable();" + "\n");
		
		function.append("data.addColumn(\'string\', \'Delta Delta G\');" + "\n");
		function.append("data.addColumn(\'number\', \'Number of miRNAs\');" + "\n");
		
		function.append("data.addRows(" + range_num + ");" + "\n");
		
		for(int i=0; i<range_num; i++){
			
			function.append("data.setCell(" + i + "," + 0 + ",\'" + range[i][0] + "\');" + "\n");
			function.append("data.setCell(" + i + "," + 1 + "," + range[i][1] + ");" + "\n");
			
			System.out.println(range[i][0] + "\t" + range[i][1]);
		}	
		
		function.append("barsVisualization = new google.visualization.ColumnChart(document.getElementById('column_chart'));" + "\n");
		function.append("barsVisualization.draw(data, {");
		
		function.append("width: " + 50*range_num + ", ");
		function.append("height: " + 400 + ", ");
		function.append("enableTooltip: " + "true" + ", ");
//		function.append("min: " + "0" + ", ");
//		function.append("max: " + "500" + ", ");
//		function.append("logScale: " + "true" + ", ");	
		function.append("title: \'" + "Column Chart of Delta Delta G Results" + "\'");
		function.append("});" + "\n");
		
//		function.append("google.visualization.events.addListener(barsVisualization, 'select', function() {" + "\n");
//		function.append("window.open(\"http://www.google.com\",\'\',\'\')" + "\n");
//		function.append("});" + "\n");
		
		function.append("google.visualization.events.addListener(barsVisualization, \'onmouseover\', barMouseOver);" + "\n");
		function.append("google.visualization.events.addListener(barsVisualization, \'onmouseout\', barMouseOut);" + "\n" );
		function.append("}" + "\n");
		
		function.append("function barMouseOver(e) {    barsVisualization.setSelection([e]);  }" + "\n");
		function.append("function barMouseOut(e) {    barsVisualization.setSelection([{\'row\': null, \'column\': null}]);  }" + "\n");
		
		// draw table
		function.append("var tableVisualization;" + "\n");
		
//		function.append("google.load(\"visualization\", \"1\", {packages:[\"table\"]});" + "\n");
		function.append("google.setOnLoadCallback(drawTable);" + "\n");
		function.append("function drawTable() {" + "\n");
		function.append("var data = new google.visualization.DataTable();" + "\n");
		
		function.append("data.addColumn(\'string\', \'miRNA\');" + "\n");
		function.append("data.addColumn(\'string\', \'Delta Delta G\');" + "\n");
		function.append("data.addColumn(\'string\', \'miRBase Link\');" + "\n");
		
		function.append("data.addRows(" + ranked.size() + ");" + "\n");
		
		int x=0;
		double max = 0;
		DecimalFormat df = new DecimalFormat("##.000");
		
		for(String miRNA: ranked.keySet()){
			
			String delta_g = df.format(ranked.get(miRNA));
			
			if(delta_g.equals(".000")){
				delta_g = "0.000";
			}
			
			function.append("data.setCell(" + x + "," + 0 + ",\'" + miRNA + "\');" + "\n");
			function.append("data.setCell(" + x + "," + 1 + ",\'" + delta_g + "\');" + "\n");
			String href = "<a href=" + "\"http://microrna.sanger.ac.uk/cgi-bin/sequences/mirna_entry.pl?acc="
						+ acc.get(miRNA) + "\" target=\"_blank\">" + acc.get(miRNA)
						+ "</a>";
			function.append("data.setCell(" + x + "," + 2 + ",\'" + href + "\');" + "\n");
			
			max = Math.max(Math.abs(ranked.get(miRNA)), max);
			
			System.out.println(miRNA + "\t" + ranked.get(miRNA));
			
			x++;
		}	
		
		function.append("tableVisualization = new google.visualization.Table(document.getElementById('result'));" + "\n");
		function.append("tableVisualization.draw(data, {");
		
		function.append("width: " + 600 + ", ");
//		function.append("height: " + 600 + ", ");
		function.append("allowHtml: " + "true" + ", ");	
//		function.append("logScale: " + "true" + ", ");	
		function.append("title: \'" + "Column Chart of Delta Delta G Results" + "\'");
		function.append("});" + "\n");
		
//		function.append("google.visualization.events.addListener(tableVisualization, 'select', function() {" + "\n");
//		function.append("window.open(\"http://www.google.com\",\'\',\'\')" + "\n");
//		function.append("});" + "\n");
		
		function.append("google.visualization.events.addListener(tableVisualization, \'onmouseover\', barMouseOver);" + "\n");
		function.append("google.visualization.events.addListener(tableVisualization, \'onmouseout\', barMouseOut);" + "\n" );
		function.append("}" + "\n");
		
		function.append("</script>");
		
		return function.toString();
	}
	
	public String gleTable(MiRandaWrapper mr, HashMap<String, String> snpInfo, String snp, String point) throws Exception{
	
		StringBuilder function = new StringBuilder();
		
		HashMap<String,String> acc = new Visualization().miRBaseAcc(mr.moopPath + "hsa-mature-miR.fasta");
		
		function.append("<script type=\"text/javascript\">" + "\n");
		function.append("var tableVisualization;");
		
		function.append("google.load(\"visualization\", \"1\", {packages:[\"table\"]});" + "\n");
		function.append("google.setOnLoadCallback(drawChart);" + "\n");
		function.append("function drawChart() {" + "\n");
		function.append("var data = new google.visualization.DataTable();" + "\n");

		function.append("data.addColumn(\'string\', \'No.\');" + "\n");
		function.append("data.addColumn(\'string\', \'miRNA\');" + "\n");
		function.append("data.addColumn(\'string\', \'Oringin\');" + "\n");
		function.append("data.addColumn(\'string\', \'Mutant\');" + "\n");
		function.append("data.addColumn(\'string\', \'Gain/Loss\');" + "\n");
		function.append("data.addColumn(\'string\', \'Start\');" + "\n");
		function.append("data.addColumn(\'string\', \'End\');" + "\n");
		function.append("data.addColumn(\'string\', \'Energy\');" + "\n");
		function.append("data.addColumn(\'string\', \'miRBase Link\');" + "\n");
		
		ArrayList<HashMap<String, String>> all = new ArrayList<HashMap<String, String>>();
		String[] allele = snp.split("/");
		int total = 0;
		
		int iRangeLeft = Integer.parseInt(snpInfo.get("position"));
		
		int maxAlleleLenght = Integer.parseInt(snpInfo.get("maxAlleleLenght"));
		int iRangeRight = iRangeLeft + maxAlleleLenght;
		
		int mut_num = 1;
		
		for(int i=0; i<allele.length; i++){
			if(allele[i].equals(point)){
				continue;
			}
			
			ArrayList<HashMap<String, String>> gle = mr.getGainEnvents("mut" + mut_num);

			for(HashMap<String,String> miRNA: gle){
				int iTargetStart = Integer.parseInt(miRNA.get("start"));
				int iTargetEnd = Integer.parseInt(miRNA.get("end"));
				
				if(iRangeLeft >= iTargetStart && iRangeRight <= iTargetEnd ){
					//				System.out.println("Include");
				}else if(iRangeRight > iTargetStart && iRangeLeft <= iTargetStart){
					//				System.out.println("Right overlap");
				}else if(iRangeLeft > iTargetStart && iRangeLeft < iTargetEnd){
					//				System.out.println("Left overlap");
				}else{
					//				System.out.println("No overlap");
					continue;
				}
				total++;
				miRNA.put("number", Integer.toString(total));
				miRNA.put("mutant", allele[i]);
				miRNA.put("target", "Gain");
				all.add(miRNA);
			}
			
			gle = mr.getLossEnvents("mut" + mut_num);

			for(HashMap<String,String> miRNA: gle){
				int iTargetStart = Integer.parseInt(miRNA.get("start"));
				int iTargetEnd = Integer.parseInt(miRNA.get("end"));
				
				if(iRangeLeft >= iTargetStart && iRangeRight <= iTargetEnd ){
					//				System.out.println("Include");
				}else if(iRangeRight > iTargetStart && iRangeLeft <= iTargetStart){
					//				System.out.println("Right overlap");
				}else if(iRangeLeft > iTargetStart && iRangeLeft < iTargetEnd){
					//				System.out.println("Left overlap");
				}else{
					//				System.out.println("No overlap");
					continue;
				}
				total++;
				miRNA.put("number", Integer.toString(total));
				miRNA.put("mutant", allele[i]);
				miRNA.put("target", "Loss");
				all.add(miRNA);
			}
			
			mut_num++;
		}
		
		function.append("data.addRows(" + total + ");" + "\n");
		
		int x=0;
		
		for(HashMap<String,String> miRNA: all){
			int y=0;
			function.append("data.setCell(" + x + "," + (y++) + ",\'" + miRNA.get("number") + "\');" + "\n");
			function.append("data.setCell(" + x + "," + (y++) + ",\'" + miRNA.get("miRNA") + "\');" + "\n");
			function.append("data.setCell(" + x + "," + (y++) + ",\'" + point + "\');" + "\n");
			function.append("data.setCell(" + x + "," + (y++) + ",\'" + miRNA.get("mutant") + "\');" + "\n");
			function.append("data.setCell(" + x + "," + (y++) + ",\'" + miRNA.get("target") + "\');" + "\n");
			function.append("data.setCell(" + x + "," + (y++) + ",\'" + miRNA.get("start") + "\');" + "\n");
			function.append("data.setCell(" + x + "," + (y++) + ",\'" + miRNA.get("end") + "\');" + "\n");
			function.append("data.setCell(" + x + "," + (y++) + ",\'" + miRNA.get("energy") + "\');" + "\n");
			String href = "<a href=" + "\"http://microrna.sanger.ac.uk/cgi-bin/sequences/mirna_entry.pl?acc="
					+ acc.get(miRNA.get("miRNA")) + "\" target=\"_blank\">" + acc.get(miRNA.get("miRNA"))
					+ "</a>";
			function.append("data.setCell(" + x + "," + (y++) + ",\'" + href + "\');" + "\n");
			x++;
		}
		
		function.append("tableVisualization = new google.visualization.Table(document.getElementById('result'));" + "\n");
		function.append("tableVisualization.draw(data, {");
		
		function.append("width: " + 800 + ", ");
		function.append("height: " + 500 + ", ");
		function.append("enableTooltip: " + "true" + ", ");
		function.append("allowHtml: " + "true" + ", ");	
		function.append("title: \'" + "Column Chart of Delta Delta G Results" + "\'");
		function.append("});" + "\n");
		
//		function.append("google.visualization.events.addListener(tableVisualization, 'select', function() {" + "\n");
//		function.append("window.open(\"http://www.google.com\",\'\',\'\')" + "\n");
//		function.append("});" + "\n");
		
		function.append("google.visualization.events.addListener(tableVisualization, \'onmouseover\', barMouseOver);" + "\n");
		function.append("google.visualization.events.addListener(tableVisualization, \'onmouseout\', barMouseOut);" + "\n" );
		function.append("}" + "\n");
		
		function.append("function barMouseOver(e) {    tableVisualization.setSelection([e]);  }" + "\n");
		function.append("function barMouseOut(e) {    tableVisualization.setSelection([{\'row\': null, \'column\': null}]);  }" + "\n");
		
		function.append("</script>");
				
		return function.toString();
	}
	
	public HashMap<String,String> miRBaseAcc(String path) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
		
		String line = null;
		
//		>hsa-let-7a MIMAT0000062 Homo sapiens let-7a
		
		HashMap<String,String> acc = new HashMap<String,String>();
		
		while((line = br.readLine()) != null){
			if(line.startsWith(">")){
				String[] id = line.replace(">", "").split(" ");
				acc.put(id[0], id[1]);			
			}
		}
		
		br.close();
		
		return acc;
	}
}
